package util.completable_future;

import exception.MyException;
import gnu.io.SerialPort;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.Common;
import util.LoadConfigInfo;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

public class GetSerialPortDataSupplier implements Supplier<String> {

    private final static Logger logger = LoggerFactory.getLogger(GetSerialPortDataSupplier.class);

    /**
     * 读取配置文件
     */
    private final LoadConfigInfo loadConfigInfo = new LoadConfigInfo();

    private final SerialPort serialPort;

    public GetSerialPortDataSupplier(SerialPort serialPort) {
        this.serialPort = serialPort;
    }

    @Override
    public String get() {
        String recv = "";
        InputStream inputStream = null;
        try {
            //获得串口的输入流
            inputStream = serialPort.getInputStream();
            int size = 0;
            int wait = 5;       //读取5次还是0则退出循环，避免死循环，用于检测分包传输
            while ((size == 0) && (wait-- > 0)){
                size = inputStream.available();
            }
            logger.info("inputStream.available: {}", size);
            if (size > 0){
                byte[] tp = new byte[1];
                List<Byte> list = new ArrayList<>();
                while (inputStream.read(tp) > 0){
                    list.add(tp[0]);
                }
                recv = new String(Common.listByteToByte(list), loadConfigInfo.getSerialPortReadDataCharsetName());
                logger.info("接收的数据长度：{}", list.size());
            }
            else {
                logger.info("inputStream.available <= 0");
            }
            //logger.info("读取到的数据：{}", builder);
        } catch (IOException e) {
            try {
                throw new MyException("串口读取数据时 IO 异常！");
            } catch (MyException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                try {
                    throw new MyException("关闭串口读取流时 IO 异常！");
                } catch (MyException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return recv;
    }


}